package lib

import (
	"encoding/json"
	"log"

	"github.com/kirinlabs/HttpRequest"
)

func CallProcessor(processer *Processer, messageJson string, queue Queue) string {
	var err error
	url := processer.CallUrl

	req := HttpRequest.NewRequest()
	var res *HttpRequest.Response
	if processer.ToOtherCenter == 1 {
		//夸中心
		postData := map[string]interface{}{
			"message":      messageJson,
			"masterServer": processer.OtherCenterUrl.String,
			"queueName":    queue.Name.String,
			"username":     "tiens",
			"password":     "com.tiens.www3",
			"sync":         "0",
			"isTopic":      "0",
			"persistent":   "0",
			"ackType":      "1",
		}
		res, err = req.Post(url, postData)
	} else {
		req.SetHeaders(map[string]string{
			"Content-Type": "application/json",
		})
		res, err = req.Post(url, messageJson)
	}

	var body string
	if err != nil {
		messageMap := make(map[string]string)
		messageMap["status"] = "00505"
		messageMap["message"] = "调用业务系统接口出错, 超时或其他错误"
		messageMap["messageJson"] = messageJson
		log.Print(messageMap, err)
		bodyByte, _ := json.Marshal(messageMap)
		body = string(bodyByte)
	} else {
		if res.StatusCode() == 200 {
			bodyRes, _ := res.Body()
			body = string(bodyRes)
			log.Print("调取"+url+"接口成功: 系统接口返回数据：", body)
		} else {
			messageMap := make(map[string]string)
			messageMap["status"] = "00506"
			messageMap["message"] = "调用业务系统接口出错,访问错误"
			messageMap["messageJson"] = ""
			bodyByte, _ := json.Marshal(messageMap)
			body = string(bodyByte)
		}
	}
	return body
}
